from scrapy.http import TextResponse, HtmlResponse
from scrapy import log

class Handler():
  def __init__(self, response):
    self.url = response.url
    self.body = response.body
    try:
      self.contentType = response.headers['Content-Type']
    except KeyError:
      self.contentType = "unknown"

    if isinstance(response, TextResponse) or isinstance(response, HtmlResponse):
      self.handleTextResponse(self.body)
    elif self.contentType == "unknown":
      log.msg("Handler: Can't get content type, try as binary", level=log.WARNING)
      self.handleBinaryResponse(self.body)
      print("Handler: handle unknow type")
    else:
      log.msg("Handler: Non-Text type: %s, treat as binary" % response.headers['Content-Type'], level=log.INFO)
      self.handleBinaryResponse(self.body)
      print("Handler: handle binary type: %s" % self.contentType)

  def handleTextResponse(self, html):
    print(html[:100])

  def handleBinaryResponse(self, binary):
    print(self.contentType)
